<?php

declare(strict_types=1);
namespace App\Common\Logic;

use App\Exception\ApiServerException;
use App\Exception\ThirdPartyException;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class FileLogic
{

    private $upload_path = UPLOADS_PATH;
//    private $getSize;              // 5145b
//    private $getExtension;         // png
//    private $getClientFilename;    // 客户端上传文件名 abc.png
//    private $getClientMediaType;   // image/png
//    private $fileName;             // 目标文件名
//    private $targetPath;           // 目标路径
//    private $filePath;             // 访问路径
//    private $qiniuConfig;          // 七牛云配置
//    private $getRealPath;          //
//    private $uploadContentSet;


    public function getUploadTypeByModule($module){
        $type = config("file.module.$module");
        return $type??'local';
    }


    public function uploadFile($file, $module, $fileNameType = 'keep')
    {
        $uniqidCode = getUniqidCode();
        $getRealPath = $file->getRealPath();
        $fileType = $this->getUploadTypeByModule($module);
        if ($fileNameType=='keep'){
            $fileName = $file->getClientFilename();
            $filePath = '/uploads/' . $module . '/' . $uniqidCode . '/';
        }else{
            $getExtension = $file->getExtension();
            $fileName = $uniqidCode.$getExtension;
            $filePath = '/uploads/' . $module . '/';
        }
        $targetPath = $this->upload_path . $filePath . $fileName;

        // 存储路径
        if (!file_exists($this->upload_path . $filePath)) {
            mkdir($this->upload_path . $filePath, 0755, true);
        }

        $fileFactory = container()->get(\Hyperf\Filesystem\FilesystemFactory::class);

        if ($fileType){
            $fileFactory = $fileFactory->get($fileType);
        }
        $stream = fopen($getRealPath, 'r+');
        $res = $fileFactory->writeStream(
            $filePath . $fileName,
            $stream
        );
        fclose($stream);

        if ($res){
            switch ($fileType){
                case 'local':
                    return callback(true,['targetPath'=>$targetPath,'filePath'=>$filePath . $fileName],'成功');
                case 'qiniu':
                    return callback(true,['filePath'=>config('file.storage.qiniu.domain').$filePath . $fileName],'成功');
            }
        }
        throw new ApiServerException('图片上传失败');
    }


    public function base64_img(string $base64): string
    {
        $regex = Regex::BASE64_IMG;
        preg_match($regex, $base64, $matchRes);
        if (!$matchRes) {
            throw new ValidateException('base64图片格式不正确');
        }
        $this->saveName .= '.' . $matchRes[1];

        $path = $this->saveDir . $this->saveName;
        $save = file_put_contents($path, base64_decode($matchRes[2]));
        if (!$save) {
            write_log('保存图片失败 ' . json_encode([$save]), __FUNCTION__, __CLASS__);
            throw new \Exception('保存失败');
        }

        return str_replace(STORAGE_PATH, '', $path);
    }

    public function file(UploadedFile $file): string
    {
        $this->saveName .= '.' . $file->getExtension();

        $path = $this->saveDir . $this->saveName;

        $file->moveTo($path);

        return str_replace(STORAGE_PATH, '', $path);
    }

}
